using System;
using System.Collections.Generic;
using System.IO;
using System.Timers;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Support.Design.Widget;
using Android.Support.V4.App;
using Android.Support.V4.View;
using Android.Support.V4.Widget;
using Android.Support.V7.App;
using Android.Support.V7.Widget;
using Android.Text;
using Android.Text.Style;
using Android.Util;
using Android.Views;
using Android.Widget;
using Com.Gcssloop.Widget;
using mb;
using mb.Droid;

namespace libmp
{
    public class CountryPickView
    {
        static ILog logger = App.logger;

        MyDialogFragment myFragment;
        ViewGroup rootLayout;
        StartActivity ctx = StartActivity.This;

        class CountryItem
        {
            public string country_name_cn;
            public string country_code;
        }
        List<CountryItem> dataSource;

        string selectedCountry;
        public Action<string, string> OnSelect;
        public CountryPickView(string init = null)
        {
            var str = File.ReadAllText($"{App.HotStorageRoot}/res/worldcountry.json");
            dataSource = LitJson.JsonMapper.ToObject<List<CountryItem>>(str);
            selectedCountry = init;
            logger.Log("country data", dataSource.Count, selectedCountry);
        }

        public MyDialogFragment CreateFragment()
        {
            bool useTitle = false;
            // useTitle = true;
            return myFragment = new MyDialogFragment()
            {
                MyOnCreate = (frag, bundle) =>
                    {
                        // frag.Cancelable = false;
                        if (useTitle)
                        {
                            frag.SetStyle((int) DialogFragmentStyle.Normal, mb.DroidLib.Resource.Style.DialogWithTitle);
                        }
                    },
                    MyOnCreateView = (frag, container) =>
                    {
                        if (useTitle)
                        {
                            // frag.Dialog.Window.SetBackgroundDrawable(new ColorDrawable(Color.Transparent));
                            frag.Dialog.SetTitle("选择国家");
                        }
                        else
                        {
                            // frag.Dialog.Window.RequestFeature(WindowFeatures.NoTitle);
                        }
                        return CreateView(frag);
                    },
                    MyOnResume = (frag) =>
                    {
                        var ss = mb.Droid.Util.GetWindowSize();
                        int w = (int) (ss.X * 0.85);
                        int h = (int) (ss.Y * 0.75);
                        // frag.Dialog.Window.SetLayout(w, h);
                        var lp = frag.Dialog.Window.Attributes;
                        lp.Width = w;
                        lp.Height = h;
                        frag.Dialog.Window.Attributes = lp;
                    }
            };
        }

        void SetSelected(string country, string code)
        {
            myFragment.Dismiss();
            OnSelect(country, code);
        }

        public View CreateView(MyDialogFragment frag)
        {
            if (rootLayout != null) return rootLayout;

            rootLayout = new LinearLayout(ctx).FillParent();
            rootLayout.SetBackgroundColor(Color.Red);
            // rootLayout.AddView(
            //     new FrameLayout(ctx) { Background = new ColorDrawable(Color.Red) },
            //     new ViewGroup.LayoutParams(-1, -1)
            // );
            rootLayout.AddView(CreateListView().FillParent());
            return rootLayout;
        }

        RecyclerView CreateListView()
        {
            var adapter = new MyRecyclerAdapter();
            adapter.MyItemCount = () => dataSource.Count;
            adapter.MyGetItemViewType = p => 0;
            adapter.MyGetItemOffset = (rect, view, state) => { rect.Top = 2; };
            adapter.MyOnBindViewHolder = (h, p) => (h as MyRecyclerViewHolder).MyUpdate(p);
            adapter.MyOnCreateViewHolder = (vg, type) =>
            {
                logger.Log("create viewholder");
                Dictionary<string, object> viewData = new Dictionary<string, object>();
                bool isUpdating = false;
                Action OnSelect = () =>
                {
                    if (isUpdating) return;
                    var idx = (int) viewData.TryGet<object>("lastBindPos");
                    var data = dataSource[idx];
                    SetSelected(data.country_name_cn, data.country_code);
                };
                TextView tvName;
                RadioButton rbPick;
                View view = new LinearLayout(ctx)
                    {
                        Clickable = true,
                            Background = Util.MakeDrawableSelector(new ColorDrawable(Color.White), new ColorDrawable(Color.White.Darker(0.9f))),
                            LayoutParameters = new ViewGroup.LayoutParams(-1, Util.dpToPx(40)),
                    }.SetClickHandler((s, e) => OnSelect())
                    .AddViewEx(
                        tvName = new TextView(ctx)
                        {
                            // Background = new ColorDrawable(Color.Green),
                            Gravity = GravityFlags.CenterVertical,
                                TextAlignment = TextAlignment.ViewStart,
                        },
                        new LinearLayout.LayoutParams(-1, -1, 1) { LeftMargin = 20, }
                    ).AddViewEx(
                        rbPick = new RadioButton(ctx)
                        {
                            ButtonTintList = Util.MakeColorStateList(Util.MainColor),
                        },
                        new LinearLayout.LayoutParams(-2, -2, 0) { RightMargin = 20, }
                    );

                rbPick.CheckedChange += (s, e) => OnSelect();

                Action<int> myUpdate = (p) =>
                {
                    viewData["lastBindPos"] = p;
                    isUpdating = true;
                    var data = dataSource[p];
                    tvName.Text = data.country_name_cn;
                    rbPick.Checked = data.country_name_cn == selectedCountry;
                    isUpdating = false;
                };

                return new MyRecyclerViewHolder(view) { data = viewData, MyUpdate = myUpdate };
            };

            var layoutManager = new GridLayoutManager(ctx, 1);
            layoutManager.SetSpanSizeLookup(new MySpanSizeLookup()
            {
                MyGetSpanSize = pos => 1,
            });

            var recyclerView = new RecyclerView(new ContextThemeWrapper(ctx, mb.DroidLib.Resource.Style.ScrollbarRecyclerView));
            recyclerView.HasFixedSize = true;
            recyclerView.SetBackgroundColor(Util.MainBKColor);
            recyclerView.SetLayoutManager(layoutManager);
            recyclerView.SetAdapter(adapter);
            recyclerView.AddItemDecoration(new MyItemDecoration());

            adapter.NotifyDataSetChanged();

            if (selectedCountry != null)
            {
                int p = dataSource.FindIndex(v => v.country_name_cn == selectedCountry);
                recyclerView.ScrollToPosition(p);
            }

            return recyclerView;
        }

    }
}